<template>
    <div class="dept">
        <button @click="getDept">向后端请求数据</button>
    <button @click="is_show">新增部门</button>
    <div class="show_Add" v-if="show_Add">
        部门名称<input type="text" v-model="dept_text"><button @click="Add">确定</button>
    </div>
    <table class="Dept">
        <caption class="title">部门表</caption>
        <thead>
            <tr>
            <th>id</th>
            <th>部门名称</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            <tr v-for="(item) in dataArr" :key="item.id">
            <td v-for="(i) in item">
                {{ i }}
                <div class="show_change" v-if="i==item.name&&show_change&&dept_index==item.id">
                    <input type="text" v-model="dept_name"><button @click="Update(item.id)">确定</button>
                </div>
            </td>
            <td><button @click="deleteById(item.id)">删除</button><button @click="changeShow(item.id)">修改</button></td>
        </tr>
        </tbody>
    </table>
    </div>
</template>
<script setup lang="ts" name="Dept">
import axios from 'axios';
import { ref,onMounted } from 'vue';
interface DeptData{
    id: number,
    name: string,
    createTime: string,
    updateTime: string
}
onMounted(()=>{
    getDept();
})
let dataArr=ref<DeptData[]>([])
let dept_index=ref(-1);
let show_change=ref(false);
let show_Add=ref(false);
let dept_text=ref("");
let dept_name=ref("");
let deptName=ref<DeptData[]>([]);
async function getDept() {
    let {data}= await axios.get("http://localhost:8080/depts");
    // console.log(data.data);
    dataArr.value=data.data;
    deptName.value=data.data;
    // for(let i=0;i<dataArr.value.length;i++){
    //     console.log(dataArr.value[i]);
    // }
    // console.log("deptName",deptName.value);
}
function is_show(){
    show_Add.value=true;
    
}
async function Add(){
    show_Add.value=false;
    let {data}=await axios.post("http://localhost:8080/depts",{
        name: dept_text.value
    })
    getDept();
    console.log(data);
    dept_text.value="";
}
async function Update(id: number){
    show_change.value=false;
    let dept_date={
        id:id,
        name: dept_name.value
    }
    let {data}=await axios.put("http://localhost:8080/depts",dept_date);
    // console.log(data.data);
    dept_name.value="";
    getDept();
}
async function deleteById(id :number){
    let {data}=await axios.delete("http://localhost:8080/depts/"+id);
    // console.log(id);
    alert("删除成功");
    // console.log(data.data);
    // dataArr.value=data.data;
    getDept();
}
function changeShow(index: number){
    show_change.value=true;
    dept_index.value=index;
}
</script>
<style scoped>
.dept{
    border: 2px solid black;
    margin-bottom: 100px;
}
.Dept{
     
     width: 100%;  
     border-collapse: collapse;  
    
    th, td {  
        border: 1px solid #000000;  
        padding: 8px;  
        text-align: center;
    }  
}
</style>